//
//  HMComposePictureView.swift
//  swift-新浪微博0
//
//  Created by 赵玉忠 on 16/9/9.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

private let HMComposePictureViewCellId = "HMComposePictureViewCellId"

class HMComposePictureView: UICollectionView {
    
    // 加号按钮点击要执行的闭包
    var addImageClosure: (()->())?
    
    // 当前数据用于保存图片
    internal lazy var images: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        self.register(HMComposePictureViewCell.self, forCellWithReuseIdentifier: HMComposePictureViewCellId)
        self.dataSource = self
        self.delegate = self
    }
    
    
    /// 该方法是提供给外界向当前控件添加图片的方法
    ///
    /// - parameter image: <#image description#>
    func addImage(image: UIImage) {
        if images.count < 9 {
            images.append(image)
            reloadData()
        }else{
            SVProgressHUD.showError(withStatus: "图片数量超出限制")
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 布局子控件的时候，当前view的大小已经确定了
        // 所以我们可以在这个位置去设置itemSize
        
        let itemMargin: CGFloat = 5
        let itemWH = (self.frame.width - 2 * itemMargin) / 3
        
        // 获取到布局对象，设置条目的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        layout.minimumLineSpacing = itemMargin
        layout.minimumInteritemSpacing = itemMargin
        
    }
}

extension HMComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("点击")
        collectionView.deselectItem(at: indexPath, animated: true)
        // 要在这个地方判断是否是最后一个cell点击
        if indexPath.item == images.count {
            // 代表是最后一个cell代表是加号按钮
            // 要在这个地方通知外界去弹出控制器
            addImageClosure?()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 如果count为0或者为9的话，都不显示+按钮，否则要显示，要显示的话就多返回一个cell
        return (images.count == 0 || images.count == 9) ? images.count : images.count + 1
        // return images.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMComposePictureViewCellId, for: indexPath) as! HMComposePictureViewCell
        
        
        if indexPath.item < images.count {
            // 给cell设置数据
            let image = images[indexPath.item]
            cell.image = image
        }else{
            cell.image = nil
        }
        
        cell.deleteClickClosure = {[weak self] in
            // 在这个闭包里面删除数组里面对应位置的图片
            self?.images.remove(at: indexPath.item)
            // 刷新数据
            self?.reloadData()
        }
        return cell
    }
}

class HMComposePictureViewCell: UICollectionViewCell {
    
    
    /// 删除按钮执行的闭包
    var deleteClickClosure: (()->())?
    
    var image: UIImage? {
        didSet {
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            }else{
                imageView.image = image
                imageView.highlightedImage = image
            }
            deleteButton.isHidden = image == nil
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        // 添加子控件
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        // 添加约束
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
        }
    }
    
    @objc private func deleteButtonClick() {
        print("删除按钮点击")
        // 因为数据在上面的view的数组里面，在这个地方并不能取到数组
        // 所以需要将点击事件抛出去
        // 也就是说在这个地方要执行代理方法或者调用闭包，或者发送通知
        deleteClickClosure?()
    }
    
    // MARK: - 懒加载控件
    
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = UIViewContentMode.scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(deleteButtonClick), for: UIControlEvents.touchUpInside)
        button.setImage(UIImage(named:"compose_photo_close"), for: UIControlState.normal)
        return button
    }()
}


